package com.mallcai.bigdata.ladon.service.export.impl.handler;

import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.cake.bigdata.starter.exception.category.BusinessException;
import com.mallcai.bigdata.ladon.client.export.ExportStrategy;
import com.mallcai.bigdata.ladon.client.vo.ReportColumnVO;
import com.mallcai.bigdata.ladon.client.vo.ReportDataVO;
import com.mallcai.bigdata.ladon.service.export.impl.ExportContext;
import com.mallcai.bigdata.ladon.tools.FileUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * described :生成excel类型的文件
 *
 * @author CaKeDou
 * @date 2019-09-26 21:52
 * Modify:
 */
@Slf4j
@Component
@Order(601)
public class GenExcelHandler extends AbstractExportPreHandler {

    @Override
    public void preInternal(ExportContext exportContext) {
        if (exportContext.getExportStrategy().getFileType() != ExportStrategy.ExportFileTypeEnum.XLS &&
                exportContext.getExportStrategy().getFileType() != ExportStrategy.ExportFileTypeEnum.XLSX
                ) {
            return;
        }
        ExcelTypeEnum excelTypeEnum = exportContext.getExportStrategy().getFileType() == ExportStrategy.ExportFileTypeEnum.XLS ? ExcelTypeEnum.XLS : ExcelTypeEnum.XLSX;
        try {
            FileUtil.createOrExistsFile(exportContext.getFilePath());
            OutputStream out = new FileOutputStream(exportContext.getFilePath());
            ReportDataVO reportDataVO = exportContext.getTargetData();
            ExcelWriter writer = new ExcelWriter(out, excelTypeEnum, true);
            List<ReportColumnVO> columns = reportDataVO.getColumns();
            List<String> keys = reportDataVO.getColumns().stream().map(t -> t.getName()).collect(Collectors.toList());
            List<List<String>> datas = reportDataVO.getRows().stream().map(t -> {
                List<String> r = new ArrayList<>();
                for (String key : keys) {
                    t.entrySet().forEach(a -> {
                        if (StringUtils.equals(a.getKey(), key)) {
                            r.add(String.valueOf(a.getValue()));
                            return;
                        }
                    });
                }
                return r;
            }).collect(Collectors.toList());
            datas.add(0, columns.stream().map(t -> StringUtils.isNotBlank(t.getShowName()) ? t.getShowName() : t.getName()).collect(Collectors.toList()));
            writer.write(datas);
            writer.finish();
        } catch (Exception e) {
            log.error("生成EXCEL文件异常", e);
            throw new BusinessException("生成EXCEL文件异常");
        }
    }

}
